﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.Mvc;

namespace Webbness.Mvc.Extensions
{
    public static class HtmlHelperExtensions
    {
        public static string BeginFieldset(this HtmlHelper htmlHelper)
        {
            return FieldsetHelper(htmlHelper, null, null, null);
        }

        public static string BeginFieldset(this HtmlHelper htmlHelper, string legendtext)
        {
            return FieldsetHelper(htmlHelper, null, legendtext, null);
        }

        public static string BeginFieldset(this HtmlHelper htmlHelper, IDictionary<string, object> fieldsetAttributes)
        {
            return FieldsetHelper(htmlHelper, fieldsetAttributes, null, null);
        }

        public static string BeginFieldset(this HtmlHelper htmlHelper, IDictionary<string, object> fieldsetAttributes, string legendtext)
        {
            return FieldsetHelper(htmlHelper, fieldsetAttributes, legendtext, null);
        }

        public static string BeginFieldset(this HtmlHelper htmlHelper, IDictionary<string, object> fieldsetAttributes, string legendtext, IDictionary<string, object> legendAttributes)
        {
            return FieldsetHelper(htmlHelper, fieldsetAttributes, legendtext, legendAttributes);
        }

        private static string FieldsetHelper(this HtmlHelper htmlHelper, IDictionary<string, object> fieldsetAttributes, string legendtext, IDictionary<string, object> legendAttributes)
        {
            var sb = new StringBuilder();
            var builder = new TagBuilder("fieldset");
            builder.MergeAttributes(fieldsetAttributes);
            sb.Append(builder.ToString(TagRenderMode.StartTag));
            if (String.IsNullOrEmpty(legendtext) == false)
            {
                var fbuilder = new TagBuilder("legend");
                fbuilder.MergeAttributes(legendAttributes);
                fbuilder.SetInnerText(legendtext);
                sb.Append(fbuilder.ToString());
            }
            return sb.ToString();
        }

        public static string EndFieldset(this HtmlHelper htmlHelper)
        {
            return "</fieldset>";
        }
    }
}